package com.ruoyi.trackapply.component;

import cn.hutool.core.util.ReflectUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.List;

/**
 * 定轨  特殊的序列化  因为字段需拼接  模型名字
 */
@JsonFormat
public class DjVOJsonSerializer extends JsonSerializer {
    @Override
    public void serialize(Object ocVO, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        Field[] fields = ocVO.getClass().getDeclaredFields();
        String modelName = (String)ReflectUtil.getFieldValue(ocVO, "model");
        jsonGenerator.writeStartObject();
        for (int i = 0; i < fields.length; i++) {
            if ("model".equals(fields[i].getName())) continue;
            List<BigDecimal> fieldValue = (List)ReflectUtil.getFieldValue(ocVO, fields[i]);
            int size = fieldValue.size();
            String[] strs = new String[size];
            for (int y = 0; y < size; y++) {
                strs[y] = fieldValue.get(y).toPlainString();
            }
            jsonGenerator.writeFieldName(modelName+"-"+fields[i].getName());
            jsonGenerator.writeArray(strs,0,strs.length);
        }
        jsonGenerator.writeEndObject();
    }
}
